<script setup>
import { User, Lock, UserFilled,Message,View, Hide} from '@element-plus/icons-vue'
import { ref } from 'vue'
import {ElMessage} from "element-plus";
import { useRouter} from "vue-router";
//控制注册与登录表单的显示， 默认显示注册
const isRegister = ref(false)

// 控制忘记密码与登入表单的显示，默认显示
const forGet=ref(false);

// 控制登入表单的显示，默认显示
const loginn=ref(true);

//用于注册的数据模型
const registerData = ref({
  username: '',
  password: '',
  nickname:'',
  email:''
})


//用于注册的表单校验模型
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 10, message: '用户名的长度必须为2~10位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 12, message: '密码长度必须为5~12位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 5, max: 12, message: '密码长度必须为5~12位', trigger: 'blur' }
  ],
  nickname:[
    {required:true,message:'请输入昵称',trigger:"blur"},
    {min:2,max:10,message:'昵称长度为2到10个字符',trigger:"blur"}
  ],
  email:[
    {required:true,message:'请输入邮箱',trigger:"blur"},
    {type:'email',message:'请输入正确的邮箱格式',trigger:"blur"}
  ]
})
import {mangerRegisterService} from "@/api/manger";

// 注册
const register = async ()=>{
  let result =  await  mangerRegisterService(registerData.value);
  ElMessage.success(result.msg ? result.msg:'注册成功');
  isRegister.value = false;
  loginn.value = true;
  clearRegisterData();
}

// 登入
import {mangerLoginService,sendVc,getVc,updateForgetPwd} from '@/api/manger'
const router = useRouter()
import { useTokenStore } from '@/Stores/token.js'
const tokenStore = useTokenStore();
const login = async () => {
  let result = await mangerLoginService(registerData.value);
  tokenStore.setToken(result.data)
  ElMessage.success(result.msg ? result.msg : '登录成功');
  router.push('/')
}


//跳转不同窗口,必须的清空输入框数据
const clearRegisterData = () => {
  registerData.value = {
    username: '',
    password: '',
    email: '',
    nickname: '',
  }
  inVcode.value = ''
}

//用户输入正确的验证码后，才能显示的修改密码框
const showPwd = ref(false);

//请求后台执行发送验证码
const sendVcode = async () => {
  let result = await sendVc(registerData.value);
  ElMessage.success(result.msg ? result.msg : '发送成功');
}

//从后台获取验证码并验证验证码
const getVcode = async () => {
  try {
    let result = await getVc(registerData.value);
    if (inVcode.value === result.data) {
      ElMessage.success(result.msg ? result.msg : '验证码正确')
      loginn.value = false
      forGet.value = false
      isRegister.value = false
      showPwd.value = true

    } else {
      ElMessage.warning(result.msg ? result.msg : '验证码错误')
    }
  } catch (error) {
    ElMessage.error('获取验证码时出错，请重试');
  }

};
//用户输入的验证码
const inVcode = ref('');

//用户验证成功后，点击眼睛图标控制输入的密码是否显示出来
const passwordVisible = ref(false);
const togglePasswordVisibility = () => {
  passwordVisible.value = !passwordVisible.value; // 切换可见性
};
const updateForgetPassword = async () => {
  try {
    let result = await updateForgetPwd(registerData.value);
    ElMessage.success(result.msg ? result.msg : '更新密码成功');
    forGet.value = false
    isRegister.value = false
    showPwd.value = false
    loginn.value = true
    clearRegisterData()
  } catch (error) {
    ElMessage.error('更新密码失败，请重试');
    console.error("更新密码时出错:", error);
  }
}
</script>

<template>
  <div class="card-container">
    <el-card class="box-card">
      <el-col class="form">
        <!-- 注册表单 -->
        <el-form ref="form" @keyup.enter.native="register" size="10px" autocomplete="off" v-if="isRegister"
                 :model="registerData" :rules="rules">
          <h1>注册</h1>
          <el-form-item prop="username">
            <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码"
                      v-model="registerData.password"></el-input>
          </el-form-item>
          <el-form-item prop="nickname">
            <el-input :prefix-icon="UserFilled" placeholder="请输入昵称" v-model="registerData.nickname"></el-input>
          </el-form-item>
          <el-form-item prop="email">
            <el-input @keyup.enter="register" :prefix-icon="Message" placeholder="请输入邮箱"
                      v-model="registerData.email"></el-input>
          </el-form-item>

          <!-- 注册按钮 -->
          <el-form-item>
            <el-button class="button" type="primary" @click="register" auto-insert-space>
              注册
            </el-button>
          </el-form-item>
          <el-form-item class="flex">
            <el-link type="info" :underline="false"
                     @click="isRegister = false;loginn=true;forGet=false; clearRegisterData()">
              ← 返回
            </el-link>
          </el-form-item>
        </el-form>

        <!-- 登录表单 -->
        <el-form ref="form" :model="form" @keyup.enter.native="login" size="12px" autocomplete="off" v-if="loginn">
          <h1>登录</h1>
          <el-form-item>
            <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
          </el-form-item>
          <el-form-item>
            <el-input @keyup.enter="login" name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码"
                      v-model="registerData.password"></el-input>
          </el-form-item>

          <el-form-item class="flex">
            <div class="flex">
              <el-checkbox>记住我</el-checkbox>
              <el-link type="primary" :underline="false"
                       @click="forGet=true;isRegister=false;loginn=false;clearRegisterData()">忘记密码？
              </el-link>
            </div>
          </el-form-item>

          <!-- 登录按钮 -->
          <el-form-item>
            <el-button class="button" type="primary" @click="login" auto-insert-space>登录</el-button>
          </el-form-item>
          <el-form-item class="flex">
            <el-link type="info" :underline="false"
                     @click="isRegister = true; forGet=false;loginn=false;clearRegisterData()">
              注册 →
            </el-link>
          </el-form-item>
        </el-form>

        <!--忘记密码-->
        <el-form ref="form" size="12px" autocomplete="off" v-if="forGet" :model="registerData" :rules="rules">
          <h1>忘记密码</h1>
          <el-form-item prop="username">
            <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
          </el-form-item>
          <el-form-item prop="email">
            <div class="send">
              <el-input style="width: 160px" :prefix-icon="Message" placeholder="请输入邮箱" v-model="registerData.email"></el-input>
              <el-button type="info" @click="sendVcode" style="width: 80px">发送验证码</el-button>
            </div>
          </el-form-item>
          <el-form-item>
            <el-input @keyup.enter="getVcode" :prefix-icon="Message" placeholder="请输入验证码"
                      v-model="inVcode"></el-input>
          </el-form-item>

          <el-form-item>
            <div class="flex">
              <el-button @click="getVcode" type="primary" auto-insert-space>
                确认
              </el-button>
              <el-button type="primary" :underline="false"
                         @click="loginn=true;forGet=false;isRegister=false;showPwd=false;clearRegisterData()"
                         auto-insert-space>
                取消
              </el-button>
            </div>
          </el-form-item>
        </el-form>
        <el-form ref="form" size="12px" autocomplete="off" v-if="showPwd" :model="registerData" :rules="rules">
          <el-form-item prop="username">
            <el-input disabled :prefix-icon="User" placeholder="" v-model="registerData.username"></el-input>
          </el-form-item>
          <el-form-item prop="email">
            <el-input disabled :prefix-icon="Message" placeholder="" v-model="registerData.email"></el-input>
          </el-form-item>
          <el-form-item prop="newPassword">
            <el-input @keyup.enter="updateForgetPassword" :type="passwordVisible ? 'text' : 'password'"
                      :prefix-icon="Lock" type="password" placeholder="请输入新密码" v-model="registerData.password">

              <template #suffix>
                <el-icon @click="togglePasswordVisibility" style="cursor: pointer">
                  <el-icon v-if="passwordVisible">
                    <View/>
                  </el-icon>
                  <el-icon v-else>
                    <Hide/>
                  </el-icon>
                </el-icon>
              </template>

            </el-input>
          </el-form-item>
          <el-form-item>
            <div class="flex">
              <el-button @click="updateForgetPassword" type="primary" auto-insert-space>
                确认
              </el-button>
              <el-button type="primary" :underline="false"
                         @click="loginn=true;showPwd=false;forGet=false;isRegister=false;clearRegisterData()"
                         auto-insert-space>
                取消
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-col>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
/* 样式 */
.card-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  height: 100vh; /* 容器高度 */
}

.box-card {
  padding: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 50vh;
  height: 55vh;
}

.bg {
  //background: url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
  //url('@/assets/login_bg.jpg') no-repeat center / cover;
  border-radius: 0 20px 20px 0;
}

.form {
  display: flex;
  flex-direction: column;
  justify-content: center;
  user-select: none;

  h1 {
    display: flex;
    justify-content: center;
    margin-top: 1px;
  }


  .button {
    width: 100%;
    margin-bottom: 0;
  }

  .flex {
    width: 100%;
    display: flex;
    justify-content: space-between;
    margin-top: 0;
    margin-bottom: 4px;
  }

  .send{
    width: 100%;
    display: flex;
    justify-content:space-between;

  }
}

</style>
